package com.example.douyinserver.collector;

import java.io.IOException;



import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.Map;
//JSON转换
@RestController
@AllArgsConstructor
public class turnToJson {
    SQLserver ss;

    {
        try {
            ss=new SQLserver();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value="/douyin/feed",method= RequestMethod.GET)
    public String getfeed() throws JsonProcessingException, ClassNotFoundException {

        return toJsonString(new feed());
    }

    @RequestMapping(value="/douyin/user/register",method= RequestMethod.POST)
    public String register(HttpServletRequest request)
            throws JsonProcessingException, ClassNotFoundException, SQLException {
        Long id=101l;
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String sql=ss.addNewUserSQL(id,username,password,username,"salt","token",0l,0l);
        System.out.println(sql);
        ss.update(sql);
        return toJsonString(new register());
    }
    //存在的问题：用户名相同问题
    @RequestMapping(value="/douyin/user/login",method= RequestMethod.POST)
    public String login(HttpServletRequest request)
            throws JsonProcessingException, ClassNotFoundException, SQLException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String sql=ss.login(username,password);
        ResultSet rs = ss.select(sql);
        signin sg=new signin();
        sg.setStatusMsg("200OK");
        if(rs.next()){
            sg.setStatusCode(0L);
            sg.setToken(rs.getString("usertoken"));
            sg.setUserID(rs.getLong("id"));
        }
        else {
            sg.setStatusCode(1L);
            sg.setToken("");
            sg.setUserID(0l);
        }
        return toJsonString(sg);
    }


    // Date-time helpers
    private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
            .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
            .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
            .appendOptional(DateTimeFormatter.ISO_INSTANT)
            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            .toFormatter()
            .withZone(ZoneOffset.UTC);

    public static OffsetDateTime parseDateTimeString(String str) {
        return ZonedDateTime.from(turnToJson.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
    }

    private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
            .appendOptional(DateTimeFormatter.ISO_TIME)
            .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
            .parseDefaulting(ChronoField.YEAR, 2020)
            .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
            .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
            .toFormatter()
            .withZone(ZoneOffset.UTC);

    public static OffsetTime parseTimeString(String str) {
        return ZonedDateTime.from(turnToJson.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
    }
    // Serialize/deserialize helpers

    public static turnToJson fromJsonString(Object obj,String json) throws IOException, ClassNotFoundException {
        return getObjectReader(obj).readValue(json);
    }

    public static String toJsonString(Object obj) throws JsonProcessingException, ClassNotFoundException {
        return getObjectWriter(obj).writeValueAsString(obj);
    }

    private static ObjectReader reader;
    private static ObjectWriter writer;

    private static void instantiateMapper(String classname) throws ClassNotFoundException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.findAndRegisterModules();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        SimpleModule module = new SimpleModule();
        module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
            @Override
            public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                String value = jsonParser.getText();
                return turnToJson.parseDateTimeString(value);
            }
        });
        mapper.registerModule(module);
        reader = mapper.readerFor(Class.forName(classname));
        writer = mapper.writerFor(Class.forName(classname));
    }

    private static ObjectReader getObjectReader(Object obj) throws ClassNotFoundException {
        System.out.println(obj.getClass().getName());
        if (reader == null) instantiateMapper(obj.getClass().getName());
        return reader;
    }

    private static ObjectWriter getObjectWriter(Object obj) throws ClassNotFoundException {
        if (writer == null) instantiateMapper(obj.getClass().getName());
        return writer;
    }

    public static void main(String args[]) throws JsonProcessingException, ClassNotFoundException {
        System.out.println(turnToJson.toJsonString(new register()));
    }
}
